package com.pronhub.luowowo.comment.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.pronhub.luowowo.comment.domain.StrategyComment;
import com.pronhub.luowowo.comment.query.StrategyCommentQuery;
import com.pronhub.luowowo.comment.repository.IStrategyCommentRepository;
import com.pronhub.luowowo.comment.service.IStrategyCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private IStrategyCommentRepository repository; // 传统的CRUD还是可以的
    @Autowired
    private MongoTemplate template; //高级查询用到的

    @Override
    public void saveOrUpdate(StrategyComment comment) {
        repository.save(comment);
    }

    @Override
    public Page selectComment(StrategyCommentQuery qo) {
        //1查询条件的创建
        Query query = new Query();

        //根据里面的destId来查询
        if (qo.getDetailId()!=-1) {
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }


        //查询总数
        Long count = template.count(query, StrategyComment.class);

        if (count==0){
            return Page.empty();
        }
        //分页的数据
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(),
                Sort.Direction.DESC,"creatTime"
                );
        query.with(pageable);
        List<StrategyComment> list = template.find(query, StrategyComment.class);


        return new PageImpl(list,pageable,count);
    }

    @Override
    public void commentThumbUp(String toid, Long userId) {
        //最简单的CRUD用和这个
        StrategyComment comment = repository.findById(toid).get();
        //如果评论为空怎么办 不为空怎么办
        if (comment==null){
            return;
        }
        List<Long> thumbuplist = comment.getThumbuplist();
        //如果当前用户在这个点赞列表里面 取消点赞
        if (!thumbuplist.contains(userId)){
            //没有id 添加点赞 添加该id
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            thumbuplist.add(userId);
        }else {
            //有改id 删除 减1
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            thumbuplist.remove(userId);
        }
        //更新改操作
        repository.save(comment);
    }
}
